<template>
  <div>
    <el-dialog
      :title="mode==='add'?'新增栏目':'编辑栏目'"
      :visible.sync="dialogVisible"
      width="850px"
      :close-on-click-modal="false"
      @close="close"
    >
      <el-form
        ref="form"
        v-loading="false"
        :model="form"
        :rules="rules"
        label-width="110px"
        size="small"
      >
        <el-form-item label="栏目名称：" prop="title">
          <el-input v-model.trim="form.title" maxlength="4" show-word-limit class="w-200" />
        </el-form-item>
        <el-form-item label="栏目商品：" prop="ranking" class="is-required">
          <div>
            <el-select v-model="form.type" placeholder="请选择">
              <el-option label="自动从类别中获取" :value="1" />
              <el-option label="手工上架商品" :value="0" />
            </el-select>
            <el-button
              v-if="form.type==1"
              icon="el-icon-plus"
              size="small"
              round
              type="text"
              @click="addCategory"
            >选择类目</el-button>
            <el-button
              v-if="form.type==0"
              icon="el-icon-plus"
              size="small"
              round
              type="text"
              @click="addGoods"
            >增加商品</el-button>
          </div>
          <el-form-item class="is-required" :prop="typePropOptions[form.type]">
            <el-table
              v-if="form.type==0"
              :data="form.goodsList"
              style="width: 100%"
              empty-text="未选择商品"
              border
              stripe
              class="goods-container"
              size="small"
              max-height="500"
            >
              <el-table-column prop="coverImg" label="图片" width="50">
                <template slot-scope="scope">
                  <img :src="fileBaseUrl+scope.row.coverImg" alt class="cover-img">
                </template>
              </el-table-column>
              <el-table-column prop="title" label="商品" />
              <el-table-column prop="category" label="类别">
                <template slot-scope="scope">{{ scope.row.category.join('/') }}</template>
              </el-table-column>
              <el-table-column label="操作" width="80">
                <template slot-scope="scope">
                  <el-button
                    size="small"
                    round
                    type="text"
                    class="app-text-color-danger"
                    @click="delGoods(scope.$index)"
                  >删除</el-button>
                </template>
              </el-table-column>
            </el-table>
            <el-table
              v-if="form.type==1"
              :data="form.categoryList"
              style="width: 100%"
              empty-text="未选择类目"
              border
              stripe
              class="category-container"
              size="small"
              max-height="500"
            >
              <el-table-column prop="name" label="类别">
                <template slot-scope="scope">{{ scope.row.names.join(' > ') }}</template>
              </el-table-column>
              <el-table-column label="操作" width="80">
                <template slot-scope="scope">
                  <el-button
                    size="small"
                    round
                    type="text"
                    class="app-text-color-danger"
                    @click="delCategory(scope.$index)"
                  >删除</el-button>
                </template>
              </el-table-column>
            </el-table>
          </el-form-item>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button size="small" :disabled="loading" round @click="hide">取 消</el-button>
        <el-button size="small" :disabled="loading" round type="primary" @click="submit">确 定</el-button>
      </div>
    </el-dialog>
    <!-- 组件 -->
    <DialogGoods ref="dialogGoods" />
    <DialogCategory ref="dialogCategory" />
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import {
  saveShelf,
  updateShelfCategory
} from '@/views/wxaMallModule/api/shelf'
import DialogGoods from './DialogGoods'
import DialogCategory from './DialogCategory'
export default {
  components: {
    DialogGoods,
    DialogCategory
  },
  data() {
    return {
      // 校验字段
      rules: {
        title: [
          {
            required: true,
            message: '请输入栏目名称',
            trigger: ['blur', 'change']
          }
        ],
        categoryList: [
          {
            type: 'array',
            required: true,
            message: '请选择类目',
            trigger: ['blur', 'change']
          }
        ],
        goodsList: [
          {
            type: 'array',
            required: true,
            message: '请选择商品',
            trigger: ['blur', 'change']
          }
        ]
      },
      // 配置
      resolve: null,
      reject: null,
      typePropOptions: {
        0: 'goodsList',
        1: 'categoryList'
      },
      // 状态
      dialogVisible: null,
      loading: false,
      // 数据
      mode: 'add',
      activeCategory: null, // 当前激活的分组
      form: {
        categoryList: [],
        description: '',
        goodsList: [],
        title: null,
        type: 1
      }
    }
  },
  computed: {
    ...mapGetters(['fileBaseUrl'])
  },
  watch: {
    'form.type'() {
      this.$nextTick((res) => {
        this.$refs.form.clearValidate(['categoryList', 'goodsList'])
      })
    }
  },
  methods: {
    /**
       * 弹框相关
       */
    open({ mode = 'add', activeCategory, row = null }) {
      this.mode = mode
      this.activeCategory = activeCategory
      if (mode == 'edit') {
        if (!row.goodsList) row.goodsList = []
        if (!row.categoryList) row.categoryList = []
        this.form = JSON.parse(JSON.stringify(row))
      }
      this.show()
      return new Promise((resolve, reject) => {
        this.resolve = resolve
        this.reject = reject
      })
    },

    show() {
      this.dialogVisible = true
    },

    close() {
      this.form = {
        categoryList: [],
        description: '',
        goodsList: [],
        title: null,
        type: 1
      }
      this.$refs.form.resetFields()
      this.loading = false
    },

    hide() {
      this.resolve = null
      this.reject = null
      this.dialogVisible = false
    },

    /**
       * 数据组
       */

    /**
       * 按钮组
       */
    // 确 定
    submit() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          this.loading = true
          const params = JSON.parse(JSON.stringify(this.form))
          if (params.type === 0) {
            params.categoryList = []
          } else if (params.type === 1) {
            params.goodsList = []
          }
          saveShelf(params)
            .then((res) => {
              if (this.mode == 'add') {
                this.update(res.data)
              } else {
                this.$notify({
                  title: '成功',
                  message: '保存成功',
                  type: 'success',
                  duration: 2000,
                  offset: 40
                })
                this.resolve && this.resolve()
                this.hide()
              }
            })
            .catch((err) => {
              this.loading = false
            })
            .finally(() => {})
        }
      })
    },

    // update
    update(id) {
      const params = JSON.parse(JSON.stringify(this.activeCategory))
      params.shelfList.push(id)
      params.shelfList = [...new Set(params.shelfList)]
      updateShelfCategory(params)
        .then((res) => {
          this.$notify({
            title: '成功',
            message: '保存成功',
            type: 'success',
            duration: 2000,
            offset: 40
          })
          this.resolve && this.resolve()
          this.hide()
        })
        .catch((err) => {})
        .finally(() => {
          this.loading = false
        })
    },

    // 新增类目
    addCategory() {
      const categoryIds = []
      this.form.categoryList.forEach((v) => {
        categoryIds.push(v.id)
      })
      this.$refs.dialogCategory.open({ categoryIds }).then((res) => {
        this.form.categoryList = res
        this.$refs.form.clearValidate(['categoryList'])
      })
    },

    // 删除商品
    delCategory(index) {
      this.form.categoryList.splice(index, 1)
    },

    // 新增商品
    addGoods() {
      const goodIds = []
      this.form.goodsList.forEach((v) => {
        goodIds.push(v.goodsId)
      })
      this.$refs.dialogGoods.open({ goodIds }).then((res) => {
        this.form.goodsList.push(res)
        this.$refs.form.clearValidate(['goodsList'])
      })
    },

    // 删除商品
    delGoods(index) {
      this.form.goodsList.splice(index, 1)
    }

    /**
       * 状态组
       */

    /**
       * 方法组
       */
  }
}
</script>
<style rel="stylesheet/scss" lang="scss" scoped>
  .w-200 {
    width: 200px;
  }

  .category-container {
    margin-top: 10px;
    .cell-item {
      display: flex;
    }
  }
  .goods-container {
    margin-top: 10px;
    .cover-img {
      width: 40px;
      height: 40px;
    }
  }
</style>
